# coding = utf-8
import sys
from bs4 import BeautifulSoup  # 网页解析，获取数据
import re  # 正则表达式,进行文字匹配
import urllib.request  # 指定URL，获取网页数据
import xlwt  # 进行excel操作


def main():
    baseurl = 'https://movie.douban.com/top250?start='
    datalist = getData(baseurl)
    saveData(datalist)
    askURL('https://movie.douban.com/top250')


findLink = re.compile(r'<a href="(.*)">')
findTitle = re.compile(r'<span class="title">(.*)</span>')
findInfor = re.compile(r'<p class="">(.*?)</p>', re.S)
findIntro = re.compile(r'<span class="inq">(.*)</span>')


# 获取数据
def getData(baseurl):
    datalist = []
    for i in range(10):
        url = baseurl + str(i*25)
        text = askURL(url)
        soup = BeautifulSoup(text, 'html.parser')
        for item in soup.find_all('div', class_='item'):
            data = []
            item = str(item)

            # 在data中加入电影的链接
            link = re.findall(findLink, item)
            data.append(link)

            # 在data中加入电影的名字
            title = re.findall(findTitle, item)
            if len(title) != 1:
                cTitle = title[0]
                data.append(cTitle)
                oTitle = title[1].replace("\xa0/\xa0", '')
                data.append(oTitle)
            else:
                data.append(title)
                data.append("")

            # 在data中加入电影的信息
            infor = re.findall(findInfor, item)
            infor = re.sub(r'<br/>(\s+)?', ' ', str(infor))
            infor = re.sub(r'(\\xa0)+', ' ', infor)
            data.append(infor.replace(' ', ''))

            # 在data中加入简介
            intro = re.findall(findIntro, item)
            intro = re.sub("。", '', str(intro))
            data.append(intro)

            datalist.append(data)

    return datalist


# 存储数据
def saveData(datalist):
    workBook = xlwt.Workbook(encoding='utf-8')
    worksheet = workBook.add_sheet('sheet1', cell_overwrite_ok=True)
    top = ['电影网页', '电影名称', '电影别名', '基本信息', '基本简介']
    for num in range(5):
        worksheet.write(0, num, top[num])
    for i in range(1, 251):
        for j in range(5):
            worksheet.write(i, j, datalist[i-1][j])
    workBook.save('豆瓣.xls')


# 得到指定url网页的数据
def askURL(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.62 "
    }  # 用户代理，表示告诉服务器我们是什么类型的机器
    req = urllib.request.Request(url, headers=headers)
    html = ''
    try:
        response = urllib.request.urlopen(req)
        html = response.read().decode('utf-8')
    except urllib.error.URLError as e:
        if hasattr(e, 'code'):
            print(e.code)
        if hasattr(e, 'reason'):
            print(e.reason)

    return html


if __name__ == '__main__':
    main()
